package com.rzico.sbl.ui.manual

import android.widget.ImageView
import android.widget.RadioGroup
import androidx.core.view.isVisible
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityManualEditBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.CommonData
import com.rzico.sbl.model.GoodsData
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.other.showManualDialog
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.goods.GoodsActivity
import com.rzico.sbl.ui.member.MemberDetailActivity
import com.rzico.sbl.ui.member.MemberTicketActivity
import com.rzico.sbl.ui.order.OrderShipWhereActivity
import com.rzico.sbl.ui.order.OrderShipWhoActivity
import com.rzico.sbl.viewmodel.ManualViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setCompoundDrawable
import com.xinnuo.common_ui.utils.showActionDialog
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.showOneHintDialog
import com.xinnuo.common_ui.utils.showTimeDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject

class ManualEditActivity : BaseActivity(R.layout.activity_manual_edit) {

    private val mBinding by lazy { ActivityManualEditBinding.bind(getRootView()) }

    // 付款方式
    private val mPayList = ArrayList<CommonData>()

    private lateinit var mReceiverId: String
    private lateinit var mCardId: String
    private lateinit var mMemberId: String
    private lateinit var mPayPlugin: String //付款插件

    private val mGoodsCount = MutableLiveData(0)
    private var mPayStatus = "" //付款状态
    private var mPayMethod = "" //付款方式
    private var mInitShopId = "" //配送初始店铺ID
    private var mShopId = ""     //配送店铺ID
    private var mAdminId = ""    //配送员ID
    private var mAdminName = ""  //配送员名称
    private var mReceiveName = ""   //收货人
    private var mReceivePhone = ""  //收货电话
    private var mReceiveAdress = "" //收货地址
    private var mReceiveLat = ""    //收货维度
    private var mReceiveLng = ""    //收货经度
    private var mHopeDate = ""      //预约时间
    private var mEstimateDate = ""  //预计送达时间
    private var isRobMode = false   //是否抢单
    private var exchangeEnable = true //是否抵扣水票

    override fun getViewModel() = get<ManualViewModel>()

    override fun initData() {
        initTitle(title = "报单编辑", name = "补报单")

        initLayout()

        getData()

        mCardId.notEmpty {
            getViewModel()
                .ticketCount(this)
        }
    }

    private fun initLayout() {
        mBinding
            .manualList
            .apply {
                isNestedScrollingEnabled = false
                layoutManager = FullyLinearLayoutManager(getIContext())

                mAdapter = SlimAdapter.creator()
                    .register<OrderGoods>(R.layout.item_manual_edit_list) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_manual_name, bean.name)
                            text(R.id.item_manual_price, bean.price.formatDecimal())
                            text(R.id.item_manual_num, "x${bean.quantity}")

                            with<ImageView>(R.id.item_manual_img) {
                                it.loadImage(bean.thumbnail)
                            }

                            clicked(R.id.item_manual_edit) {
                                showManualDialog(
                                    name = bean.name,
                                    price = bean.price.orEmpty("0.00"),
                                    defaultNum = bean.quantity,
                                    isForced = true,
                                    onSure = { price, num ->
                                        cartModify(bean.id, price, num)
                                    }
                                )
                            }

                            longClicked {
                                cartDelete(bean.id)
                                true
                            }
                        }
                    }
                    .attachTo(this)
            }

        tvRight?.oneClick {
            startActivityEx<ManualRepairActivity>(
                "receiverId" to mReceiverId,
                "cardId" to mCardId,
                "memberId" to mMemberId,
                "consignee" to mReceiveName,
                "phone" to mReceivePhone,
                "address" to mReceiveAdress
            )

            finishView()
        }
    }

    override fun initListener() {
        mPayPlugin = "cashPayPlugin"
        mReceiverId = intent.getExtra("receiverId")
        mCardId = intent.getExtra("cardId")
        mMemberId = intent.getExtra("memberId")
        mReceiveName = intent.getExtra("consignee")
        mReceivePhone = intent.getExtra("phone")
        mReceiveAdress = intent.getExtra("address")
        isRobMode = getBoolean("canRob")

        mBinding.apply {
            manualRb1.setCompoundDrawable(
                leftSize = 16f,
                leftDrawable = R.drawable.manual_ticket_selector
            )

            manualRb2.setCompoundDrawable(
                leftSize = 16f,
                leftDrawable = R.drawable.manual_ticket_selector
            )
            manualName.text = "$mReceiveName  $mReceivePhone"
            manualAdress.text = mReceiveAdress
            manualMember.isVisible = mCardId.isNotEmpty() && userRole in "1,2"
            manualTicketsLl.isVisible = mCardId.isNotEmpty()

            manualCall.oneClick {
                mReceivePhone.notEmpty {
                    showBottomPhoneDialog(this)
                }
            }

            manualAdress.longClick {
                mReceiveAdress
                    .notEmpty {
                        copyStringToClip(this)
                        showToast("地址复制成功！")
                    }
            }

            manualAdressCopy.oneClick {
                mReceiveAdress
                    .notEmpty {
                        copyStringToClip(this)
                        showToast("地址复制成功！")
                    }
            }

            manualMember.oneClick {
                (mCardId.isNotEmpty()
                        && mMemberId.isNotEmpty())
                    .condition {
                        startActivityEx<MemberDetailActivity>(
                            "cardId" to mCardId,
                            "memberId" to mMemberId
                        )
                    }
            }

            manualTicketsLl.oneClick {
                mCardId.notEmpty {
                    startActivityEx<MemberTicketActivity>(
                        "cardId" to mCardId,
                        "memberId" to mMemberId
                    )
                }
            }

            manualGroup.setOnCheckedChangeListener(this@ManualEditActivity)

            // 付款状态
            manualStatus.oneClick {
                showActionDialog(
                    "已支付", "未支付"
                ) { index, hint ->
                    manualStatus.setRightString(hint)

                    mPayStatus = if (index == 0) "paid" else "unpaid"
                    mPayMethod = ""
                    mPayPlugin = "cashPayPlugin"
                    manualPay.setRightString("")
                    manualPay.isVisible = index == 0
                }
            }

            // 付款方式
            manualPay.oneClick {
                mPayList.isNotEmpty()
                    .conditionElse(
                        actionTrue = ::showActionDialog,
                        actionFalse = { getViewModel().getPayment() }
                    )
            }

            // 配送站
            manualWhere.oneClick {
                startActivityEx<OrderShipWhereActivity>(
                    "lat" to mReceiveLat,
                    "lng" to mReceiveLng
                )
            }

            // 配送员
            manualWho.oneClick {
                mShopId.ifEmpty {
                    showToast("请选择配送站点")
                    return@oneClick
                }

                startActivityEx<OrderShipWhoActivity>("shopId" to mShopId)
            }

            // 预约时间
            manualTime.oneClick {
                val initYear =
                    TimeHelper
                        .getInstance()
                        .run {
                            getYearOfDate(stringDateShort)
                        }

                showTimeDialog(
                    maxYearValue = initYear,
                    count = 4,
                    title = "请选择预约时间",
                    isCurrentDate = true,
                    isBeforeLimited = true
                ) { _, _, _, _, _, hint ->
                    mHopeDate =
                        hint.toFormat(
                            sFormat = "yyyy-MM-dd HH时",
                            eFormat = "yyyy-MM-dd HH:mm:ss"
                        )

                    (mHopeDate.isBefore(
                        mEstimateDate.getTimeString(),
                        "yyyy-MM-dd HH:mm:ss"
                    )
                            ).conditionElse(
                            actionTrue = {
                                mHopeDate = ""

                                lifecycleScope.launch {
                                    delay(400)

                                    showOneHintDialog(
                                        hint = "预约时间不能早于预计送达时间\n${mEstimateDate.getTimeString()}"
                                    )
                                }
                            },
                            actionFalse = {
                                manualTime
                                    .apply {
                                        setRightString(mHopeDate)

                                        getView(7)
                                            .layoutParams.apply {
                                                width = dp2px(15f)
                                                height = dp2px(15f)
                                            }
                                        setRightIcon(getDrawableEx(R.mipmap.icon_arrow_close))
                                    }
                            }
                        )
                }
            }

            // 预约时间清除
            manualTime
                .getView(7)
                .oneClick {
                    mHopeDate.notEmpty {
                        mHopeDate = ""

                        manualTime
                            .apply {
                                setRightString(mHopeDate)

                                getView(7)
                                    .layoutParams.apply {
                                        width = dp2px(13f)
                                        height = dp2px(13f)
                                    }
                                setRightIcon(getDrawableEx(R.mipmap.icon_arrow))
                            }
                    }
                }

            // 添加商品
            manualAdd.oneClick {
                startActivityEx<GoodsActivity>("mode" to "single")
            }

            // 提交订单
            btSubmit.oneClick {
                when {
                    mList.isEmpty() -> {
                        showToast("请添加报单商品")
                        return@oneClick
                    }

                    mPayStatus.isEmpty() -> {
                        showToast("请选择付款状态")
                        return@oneClick
                    }

                    mPayStatus == "paid"
                            && manualStatus.isVisible
                            && mPayMethod.isEmpty() -> {
                        showToast("请选择付款方式")
                        return@oneClick
                    }

                    mShopId.isEmpty() -> {
                        showToast("请选择配送站点")
                        return@oneClick
                    }

                    mAdminId.isEmpty()
                            && mShopId == mInitShopId
                            && !isRobMode -> {
                        showToast("请选择配送人员")
                        return@oneClick
                    }
                }

                if (mList.any {
                        it as OrderGoods
                        it.type == "dummy" && it.subType == "water"
                    }) {
                    showHintDialog(
                        hint = "是否确认给客户添加水票？",
                        onSure = { submit() }
                    )
                } else submit()
            }
        }

        // 观察付款方式
        getViewModel()
            .mPayEvent
            .observe(getLifecycleOwner()) {
                mPayList.addItems(it)
                showActionDialog()
            }

        // 观察应收金额
        getViewModel()
            .mTotalEvent
            .observe(getLifecycleOwner()) {
                if (it == 0.0) {
                    mPayPlugin = "cashPayPlugin"
                    mPayStatus = "paid"
                    mPayMethod = "eleTicket"
                    mBinding.manualStatus.gone()
                    mBinding.manualPay.gone()
                } else {
                    mPayStatus = ""
                    mPayMethod = ""
                    mBinding.manualStatus.visible()
                    mBinding.manualStatus.setRightString("")
                    mBinding.manualPay.setRightString("")
                }
            }

        // 观察商品列表
        mGoodsCount
            .observe(getLifecycleOwner()) { length ->
                mBinding
                    .manualGoodsLl
                    .isVisible = length > 0

                mList.notEmpty {
                    mBinding
                        .manualNum
                        .text = sumOf {
                        it as OrderGoods
                        it.quantity.intValue
                    }.toString()

                    mBinding
                        .manualAmount
                        .text = sumOf {
                        it as OrderGoods
                        it.quantity.intValue * it.price.doubleValue
                    }.formatDecimal()
                }
            }

        // 观察会有水票总数
        getViewModel()
            .mTicketEvent
            .observe(this) {
                mBinding
                    .manualTickets
                    .text = it.toString()
            }

        // 观察配送方式
        observe<String>("orderShip") {
            val items = it.split(",")
            when (items[0]) {
                "shop" -> {
                    mShopId = items[1]
                    mAdminId = ""
                    mAdminName = ""

                    mBinding.manualWhere.setRightString(items[2])
                    mBinding.manualWho.setRightString("")

                    when {
                        mShopId != mInitShopId ->
                            mBinding
                                .manualWho
                                .setRightHintString("请选择配送人员（选填）")

                        !isRobMode && mShopId == mInitShopId ->
                            mBinding
                                .manualWho
                                .setRightHintString("请选择配送人员")
                    }
                }

                "admin" -> {
                    mAdminId = items[1]
                    mAdminName = items[2]

                    mBinding.manualWho.setRightString(items[2])
                }
            }
        }

        // 观察添加商品
        LiveEventBus
            .get("manualGoods", GoodsData::class.java)
            .observe(this) {
                getViewModel()
                    .delay {
                        showManualDialog(
                            name = it.name,
                            price = it.price,
                            isForced = true,
                            onSure = { price, count ->
                                cartAdd(it.productId, price, count)
                            }
                        )
                    }
            }
    }

    /**
     * 付款方式
     */
    private fun showActionDialog() {
        val items = mPayList.map { it.name.orEmpty() }.toTypedArray()

        showActionDialog(*items) { index, hint ->
            mPayMethod = mPayList[index].id
            mBinding.manualPay.setRightString(hint)

            mPayPlugin = conditionIf(
                mPayMethod == "monthly",
                "monthPayPlugin",
                "cashPayPlugin"
            )
        }
    }

    /**
     * 提交数据
     */
    private fun submit() {
        getViewModel()
            .goodsEdit(
                BaseUrl.manuSub,
                "shippingMethod" to "warehouse",
                "pledge" to "0",
                "pledgeQuantity" to "0",
                "exchangeEnable" to exchangeEnable,
                "receiverId" to mReceiverId,
                "memberId" to mMemberId,
                "paymentPluginId" to mPayPlugin,
                "payStatus" to mPayStatus,
                "payMethod" to mPayMethod,
                "shopId" to mShopId,
                "adminId" to mAdminId,
                "hopeDate" to mHopeDate,
                "memo" to mBinding.manualMemo.textTrim
            )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    showToast("报单提交成功！")

                    ActivityStack
                        .screenManager
                        .popActivities(
                            ManualMobileActivity::class.java,
                            ManualEditActivity::class.java
                        )
                }
            )
    }

    /**
     * 添加商品
     */
    private fun cartAdd(productId: String, amount: String, quantity: String) {
        getViewModel()
            .goodsEdit(
                BaseUrl.manuAdd,
                "id" to productId,
                "price" to amount,
                "quantity" to quantity,
                "memberId" to mMemberId
            )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    // 更新购物车
                    window.decorView.post { cartList() }

                    // 更新商品金额
                    getViewModel()
                        .cartCount(
                            mReceiverId,
                            mMemberId,
                            exchangeEnable,
                            mBinding
                        )
                }
            )
    }

    /**
     * 删除商品
     */
    private fun cartDelete(itemId: String) {
        showHintDialog(
            title = "删除商品",
            hint = "确定要删除该商品吗？",
            onSure = {
                getViewModel()
                    .goodsEdit(
                        BaseUrl.manuDel,
                        "id" to itemId
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            // 更新购物车
                            window.decorView.post { cartList() }

                            // 更新商品金额
                            getViewModel()
                                .cartCount(
                                    mReceiverId,
                                    mMemberId,
                                    exchangeEnable,
                                    mBinding
                                )
                        }
                    )
            }
        )
    }

    /**
     * 修改商品
     */
    private fun cartModify(
        itemId: String,
        price: String,
        amount: String
    ) {
        getViewModel()
            .goodsEdit(
                BaseUrl.manuEdt,
                "id" to itemId,
                "quantity" to amount,
                "price" to price
            )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    // 更新购物车
                    window.decorView.post { cartList() }

                    // 更新商品金额
                    getViewModel()
                        .cartCount(
                            mReceiverId,
                            mMemberId,
                            exchangeEnable,
                            mBinding
                        )
                }
            )
    }

    /**
     * 商品列表
     */
    private fun cartList() {
        getViewModel()
            .cartList()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    val obj = JSONObject(it)
                    val objOrder = obj.optJSONArray("cartItems") ?: JSONArray()
                    mList.clear()
                    mList.addItems(
                        JsonUtil.toList(
                            objOrder.toString(),
                            OrderGoods::class.java
                        )
                    )

                    mGoodsCount.value = mList.size

                    mAdapter.setDataList(mList)
                }
            )
    }

    /**
     * 报单信息
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .manualInfo(mReceiverId, mMemberId, exchangeEnable)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    mInitShopId = obj.optNotNull("shopId")
                    mShopId = mInitShopId
                    mAdminId = obj.optNotNull("adminId")
                    mAdminName = obj.optNotNull("adminName")
                    mEstimateDate = obj.optNotNull("estimateDate")

                    mBinding.apply {
                        // 商家备注
                        manualCmemo.text =
                            obj.optNotNull("cardMemo")
                                .notEmpty { manualCmemoLl.visible() }

                        manualWhere.setRightString(obj.optNotNull("shopName"))

                        isRobMode
                            .conditionElse(
                                actionTrue = {
                                    mAdminId = ""
                                    mAdminName = ""
                                    manualWho.setRightHintString("请选择配送人员（选填）")
                                },
                                actionFalse = {
                                    manualWho.setRightString(obj.optNotNull("mAdminName"))
                                }
                            )
                    }

                    // 更新收款金额
                    getViewModel().updatePrice(mBinding, obj)
                    // 购物车列表
                    cartList()

                    // 收货信息
                    val objReceive = obj.optJSONObject("receiver") ?: JSONObject()
                    mReceivePhone = objReceive.optNotNull("phone")
                    mReceiveLat = objReceive.optNotNull("lat")
                    mReceiveLng = objReceive.optNotNull("lng")

                    // 今日是否下单
                    val todayOffCount = obj.optNotNull("todayOffCount").intValue
                    (todayOffCount > 0).condition {
                        showOneHintDialog(
                            isForced = true,
                            hint = getString(R.string.hint_manual)
                        )
                    }
                }
            )
    }

    override fun onCheckedChanged(group: RadioGroup, checkedId: Int) {
        exchangeEnable = checkedId == R.id.manual_rb1

        mList.notEmpty {
            // 更新商品金额
            getViewModel()
                .cartCount(
                    mReceiverId,
                    mMemberId,
                    exchangeEnable,
                    mBinding
                )
        }
    }

}